import React from 'react';
import ReactDOM, { createPortal, render } from 'react-dom';
import PopUp from '../index';
import { useIntl } from 'umi';

const usePopup = () => {
  const intl = useIntl();
  const close = (containerWrap) => {
    ReactDOM.unmountComponentAtNode(containerWrap);
    document.body.removeChild(containerWrap);
  };
  const open = (props = {}) => {
    let { containerId, content, x, y, dataset } = props;
    const containerWrap = document.createElement('div');
    const container = containerId
      ? document.getElementById(containerId)
      : document.body;

    document.body.appendChild(containerWrap);

    render(
      <PopUp
        {...props}
        onClose={() => close(containerWrap)}
        style={{ left: x, top: y }}
        container={container}
      >
        {React.isValidElement(content)
          ? React.cloneElement(content, {
              dataset,
              intl,
              onClose: () => close(containerWrap),
            })
          : content}
      </PopUp>,
      containerWrap,
    );
    return containerWrap;
  };

  return {
    open,
    close,
  };
};

export default usePopup;
